package com.cn.JUC.utils.case5;

import java.util.concurrent.locks.StampedLock;

/**
 * @Title TODO
 * @Description TODO
 * @Author CAI ZHAI
 * @Date 2021/9/2 17:26
 **/
public class StampedLockImpl{
        private int x, y;
        final StampedLock sl = new StampedLock();
        /**
         * @Title 乐观读的最佳实现
         * @Description 计算到原点的距离
         **/
        double distanceFromOrigin() {
            // 乐观读
            long stamp = sl.tryOptimisticRead();
            // 读入局部变量，
            // 读的过程数据可能被修改
            int curX = x, curY = y;
            //判断执行读操作期间是否存在写操作，如果存在，则sl.validate返回false（优秀：避免while死循环）
            if (!sl.validate(stamp)){
                // 升级为悲观读锁
                stamp = sl.readLock();
                try {
                    curX = x;
                    curY = y;
                } finally {
                    //释放悲观读锁
                    sl.unlockRead(stamp);
                }
            }
            return Math.sqrt(curX * curX + curY * curY);
        }
    
    /**
     * @Title 写的最佳实现
     * @Description 模板
     **/
    public void writeLock(){
        long stamp = sl.writeLock();
        try {
            // 写共享变量
            //......
        } finally {
            sl.unlockWrite(stamp);
        }
    }
    
}
